package controllers.wx;

import cn.hutool.json.JSONObject;
import com.tom.basic.service.ServiceQueryResult;
import com.tom.basic.service.ServiceResult;
import controllers.filter.FilterPortal;
import me.chanjar.weixin.common.error.WxErrorException;
import models.WeiXinUser;
import org.apache.commons.lang.StringUtils;
import play.mvc.Controller;
import play.mvc.With;
import support.BigCate;
import support.LogUtils;
import utils.WeiXinUtils;

import java.util.HashMap;
import java.util.Map;

@With(FilterPortal.class)
public class AuthPortal extends Controller {

    public static void auth(String encryptedData, String iv, String code, String image, String nickName) throws WxErrorException {
        Map<String, String> map = new HashMap<>(3);
        JSONObject json = WeiXinUtils.getConnect(code);
        String sessionKey = json.getStr("session_key");
        String unionId = json.getStr("unionid");
        String openId = json.getStr("openid");
        map.put("sessionKey", sessionKey);
        map.put("unionId", unionId);
        map.put("openId", openId);
        String phone = "";
        if (StringUtils.isNotEmpty(encryptedData)) {
            JSONObject userInfo = WeiXinUtils.getUserInfo(encryptedData, sessionKey, iv);
            LogUtils.ERROR_LOGGER.info("联合登陆返回：{}", userInfo);
            phone = (String) userInfo.get("purePhoneNumber");
        }
        try {
            WeiXinUser user = WeiXinUser.find("isDelete = 0 and openId=:openId").setParameter("openId", openId).first();
            if (user == null) {
                user = new WeiXinUser();
                user.openId = openId;
            }
            user.phoneNumber = phone;
            user.avatarUrl = image;
            user.nickName = nickName;
            user.save();
            renderJSON(ServiceResult.asSuccess(user));
        } catch (Exception e) {
            LogUtils.ERROR_LOGGER.error("登陆失败", e);
            renderJSON(ServiceResult.asFail(e.getMessage()));
        }
    }

    /**
     * 获取小程序的大分类
     */
    public static void getBigCates() {
        renderJSON(ServiceQueryResult.asSuccess(BigCate.find("isDelete = 0 ").fetch()));
    }

}
